package book.util;


import book.exception.SystemDbException;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库工具类
 */
public class DbHelper {
    //数据源
    private static DataSource dataSource;
    //静态块，加载配置文件，创建druid连接池
    static {
        try {
            //加载配置文件，以流返回
            InputStream is = DbHelper.class.getClassLoader().getResourceAsStream("druid.properties");
            //创建属性对象
            Properties prop = new Properties();
            //属性对象加载is
            prop.load(is);
            //基于德鲁连接池类创建连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            //将异常包装成运行时异常抛出
            throw new SystemDbException("获取连接错误："+e.getMessage());
        }
    }

    /**
     * 返回连接池对象
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }
    /**
     * 从连接池中返回连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getConnection()  {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new SystemDbException("获取连接错误："+e.getMessage());
        }
    }
}
